const { execQueryUrl, contextPath, obj2Query } = require("./utils");
const VueCompiler = require("@vue/compiler-sfc");
const hash = require("hash-sum");

module.exports = function (content) {
  const param = execQueryUrl(this.resourceQuery);
  if (!param.has("vue")) {
    return splitSFC(this, content);
  } else {
    return exectCompile(this, content, param);
  }
};

function splitSFC(loaderContext, content) {
  const res = VueCompiler.parse({
    source: content,
  });
  const codes = [];
  const path = contextPath(loaderContext, loaderContext.resource);
  const id = "data-v-" + hash(path + "-" + content);
  if (Array.isArray(res.styles)) {
    res.styles.forEach((style, index) => {
      const obj = {
        id,
        vue: true,
        type: "style",
        lang: "css",
        index,
        ...style.attrs,
      };
      codes.push(`import '${path}?${obj2Query(obj)}'`);
    });
  }
  if (res.template) {
    const obj = {
      id,
      lang: "js",
      vue: true,
      type: "template",
    };
    codes.push(`import render from '${path}?${obj2Query(obj)}'`);
  }
  if (res.script) {
    const obj = {
      id,
      vue: true,
      lang: "js",
      type: "script",
      ...res.script.attrs,
    };
    codes.push(`import script from '${path}?${obj2Query(obj)}'`);
  }
  codes.push(`script.render = render`);
  codes.push(`export default script`);
  return codes.join("\n");
}
function exectCompile(loaderContext, content, param) {
  const res = VueCompiler.parse({
    source: content,
  });
  switch (param.get("type")) {
    case "style":
      return res.styles[param.get("index")].content;
    case "script":
      return VueCompiler.compileScript(res, { id: param.get("id") }).content;
    case "template":
      const code = VueCompiler.compileTemplate({
        source: res.template.content,
        id: param.get("id"),
      }).code;
      return code + "\nexport default render";
  }
}
